<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:20px;float:right">
      <el-button type="primary" @click="handleCreate">新增资讯栏目</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" prop="name" label='栏目名称' min-width="200"></el-table-column>
      <el-table-column class-name="status-col" label="栏目图标" min-width="200" align="center">
        <template slot-scope="scope">
          <div class="row-div-ctx" v-if="scope.row.icon != ''">
            <img :src="scope.row.icon" class="row-div-ctx-img"/>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="栏目背景" min-width="200" align="center">
        <template slot-scope="scope">
          <div class="row-div-ctx2" v-if="scope.row.cover != ''">
            <img :src="scope.row.cover" class="row-div-ctx-img2"/>
          </div>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="parentName" label='父级栏目' min-width="200"></el-table-column>
      <el-table-column align="center" prop="weight" label="权重" min-width="200" sortable :sortBy="['weight','createTime']"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" min-width="200" sortable >
        <template slot-scope="scope">{{scope.row.createTime|dateformat('YYYY-MM-DD HH:mm')}} </template>
      </el-table-column >
      <el-table-column align="center" label="操作" width="240">
        <template slot-scope="scope">
          <el-button size="small" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogStatus=='create' ? '新增资讯栏目' : '编辑资讯栏目'" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="栏目名称" label-width="110px" prop="name">
          <el-input v-model="form.name" auto-complete="off" maxlength="20"
          placeholder="请输入资讯栏目名称（不超过20个字）"></el-input>
        </el-form-item>
        <el-form-item label-width="110px" label="栏目图标" class="postInfo-container-item" prop="icon">
            <el-input v-model="form.icon" type='text' style='display:none'></el-input>
            <el-upload
            ref="upload"
            :headers="headers"
            action="/tools/oss/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            list-type="picture"
            :accept="'.png,.jpg,.jpeg,.gif'"
            :limit="2">
            <el-button size="small" type="primary" icon="el-icon-upload2">点击此处上传图片</el-button>
            <!-- <div slot="tip" class="el-upload__tip">注：建议尺寸：96X96px</div> -->
          </el-upload>
        </el-form-item>
        <el-form-item label-width="110px" label="栏目背景" class="postInfo-container-item" prop="cover">
            <el-input v-model="form.cover" type='text' style='display:none'></el-input>
            <el-upload
            ref="upload2"
            :headers="headers"
            action="/tools/oss/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove2"
            :on-success="handleUploadSuccess2"
            :file-list="fileList2"
            list-type="picture"
            :accept="'.png,.jpg,.jpeg,.gif'"
            :limit="2">
            <el-button size="small" type="primary" icon="el-icon-upload2">点击此处上传图片</el-button>
            <!-- <div slot="tip" class="el-upload__tip">注：建议尺寸：96X96px</div> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="权重" label-width="110px" prop="weight">
          <el-input-number  v-model="form.weight" :step="1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label-width="110px" label="父级栏目：" v-if="form.parentId != 0">
          <el-select v-model="form.parentId" placeholder="请选择">
            <el-option
              v-for="item in sections"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addForm">确 定</el-button>
        <el-button v-else type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, add, update, getId, delId, parentSection } from '@/api/advisorySection'
import { getGradeList } from '@/api/grade'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      sections:[],
      fileList:[],
      fileList2:[],
      headers:{},
      dialogStatus:'create',
      form:{
        id:0,
        icon:'',
        cover:'',
        name:'',
        weight:1
      },
      dialogFormVisible:false,
      list: null,
      listLoading: true,
      rules: {
        name: [{ required: true, message: '请输入资讯栏目名称', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入排序权重', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传图标', trigger: 'change' }],
        cover: [{ required: true, message: '请上传背景图', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.headers = { accessToken:getToken() }
    this.fetchData()
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        false:'否',
        true:'是'
      }
      return statusMap[status]
    }
  },
  methods: {
    parentSection() {
      parentSection().then(response => {
        const sections = response.data
        this.sections = sections
      })
    },
    handleUploadSuccess2(rst, file, fileList){
      const { code, data:{ picUrlList } } = rst
      const { form } = this
      if(code == 0){
        this.form.cover = picUrlList[0]
        this.fileList2 = [{ name:file.url, url:file.url }]
      }else{
        this.$refs.upload2.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    handleRemove2(file, fileList) {
      if(fileList.length == 0){
        this.form.cover = ''
        this.$refs.upload2.clearFiles()
      }
    },
    handleUploadSuccess(rst, file, fileList){
      const { code, data:{ picUrlList } } = rst
      const { form } = this
      if(code == 0){
        this.form.icon = picUrlList[0]
        this.fileList = [{ name:file.url, url:file.url }]
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      if(fileList.length == 0){
        this.form.icon = ''
        this.$refs.upload.clearFiles()
      }
    },
    handleChange(row){
      row['selected'] = !row['selected']
    },
    handleUpdate(row){
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      getId(row.id).then(response => {
        const { code, message, data } = response
        const { icon, cover } = data
        if(code == 0){
          const { from } = this
          if(icon.length != 0){
            this.fileList = [{ name:icon, url:icon }]
          }else{
            this.fileList = []
          }
          if(cover.length != 0){
            this.fileList2 = [{ name:cover, url:cover }]
          }else{
            this.fileList2 = []
          }
          this.form = data
        }else{
          this.$message(message)
        }
      })
    },
    handleCreate() {
      this.form = {
        id:0,
        icon:'',
        name:'',
        weight:1
      }
      this.fileList = []
      this.fileList2 = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    updateForm(){
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form } = this
          update(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    addForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { form } = this
          add(form).then(response => {
            const { code, message } = response
            if(code == 0){
              this.fetchData()
              this.dialogFormVisible = false
            }else{
              this.$message(message)
            }
          })
        } else {
          return false
        }
      })
    },
    fetchData() {
      this.listLoading = true
      this.parentSection()
      getList().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    handleDelete(idx, row) {
      const { id } = row
      delId(id).then(response => {
        const { code } = response
        if(code == 0){
          this.$notify({
            title: '成功',
            message: '删除栏目成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(idx)
          this.list.splice(idx, 1)
          this.total--
        }else{
          this.$notify({
            title: '失败',
            message: '删除栏目失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.row-div-ctx2{
  width:160px;
  height:80px;
  margin: 0 auto;
}
.row-div-ctx-img2{
  height:80px;
}
.row-div-ctx{
  width:48px;
  height:48px;
  overflow:hidden;
  border-radius:48px;
  margin: 0 auto;
}
.row-div-ctx-img{
  height:48px;
}
.pagination-container{
  margin-top:30px;
}
.checkbox-item{
    margin-right:30px;
    margin-left:0;
  }
</style>
